package cn.ycc1.boot3redis.service;

import cn.ycc1.boot3redis.entity.Message;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 消息生产者服务
 * @author ycc
 * @date 2025/11/20
 */
@Service
public class MessageProducerService {

    private final RedisTemplate<String, Object> redisTemplate;
    private final String messageQueueName;

    public MessageProducerService(RedisTemplate<String, Object> redisTemplate,
                                  @Value("${app.redis.queue.name}") String messageQueueName) {
        this.redisTemplate = redisTemplate;
        this.messageQueueName = messageQueueName;
    }

    /**
     * 发送消息到队列
     */
    public void sendMessage(Message message) {
        redisTemplate.opsForList().leftPush(messageQueueName, message);
        System.out.println("发送消息: " + message);
    }

    /**
     * 批量发送消息
     */
    public void sendMessages(List<Message> messages) {
        for (Message message : messages) {
            sendMessage(message);
        }
    }

    /**
     * 获取队列长度
     */
    public Long getQueueSize() {
        return redisTemplate.opsForList().size(messageQueueName);
    }
}
